import os.path
import urllib
import json
import logging
import time
# 导入uuid类
import uuid
# 导入哈希库
import hashlib
from django.db.models import Q, F
from django.http import JsonResponse
from .models import History
import jiagu
from .myner import named_entity
import pickle
import openpyxl
# 导入Setting
from django.conf import settings
import unittest
import re
from jiagu import utils
from django.shortcuts import render


# Create your views here.


def search_text(request):
    time.sleep(3)
    """对用户的输入进行处理"""
    data = json.loads(request.body.decode('utf-8'))
    try:
        with open(r'D:\Github\django\my_vue_Be\apps\search\argument.pickle', 'rb') as f:
            word_2_index = pickle.load(f)
            model = pickle.load(f)
            index_2_tag = pickle.load(f)
            device = pickle.load(f)
            """此处放对传入的text进行处理"""
            "分词操作"
            text = named_entity(word_2_index, model, index_2_tag, device, str(data['text']))
            sentences = named_entity(word_2_index, model, index_2_tag, device, str(data['text']))

        "提取关系"
        text2 = jiagu.knowledge(data['text'])
        kol = list(text2)

        if sentences is not None:
            if kol is not None:
                obj_hist = History(Ner=str(sentences), Re=str(kol), text=data['text'], username=data['username'])
                obj_hist.save()
                obj_hists = History.objects.all().values()
                hists = list(obj_hists)
                return JsonResponse({'code': 1, 'text': sentences, 'text2': kol, 'test3': hists})
            else:
                return JsonResponse({'code': 0, 'msg': "查询异常，数据2为空"})
        else:
            return JsonResponse({'code': 0, 'msg': "查询异常，数据1为空"})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "查询异常，后端错误,具体错误：" + str(e)})


def search_text_1(request):
    time.sleep(3)
    """对用户的输入进行处理"""
    data = json.loads(request.body.decode('utf-8'))
    try:
        with open(r'D:\Github\django\my_vue_Be\apps\search\argument.pickle', 'rb') as f:
            word_2_index = pickle.load(f)
            model = pickle.load(f)
            index_2_tag = pickle.load(f)
            device = pickle.load(f)
            """此处放对传入的text进行处理"""
            "分词操作"
            text = named_entity(word_2_index, model, index_2_tag, device, str(data['text']))
            sentences = named_entity(word_2_index, model, index_2_tag, device, str(data['text']))

        "提取关系"
        text2 = jiagu.knowledge(data['text'])
        kol = list(text2)

        if sentences is not None:
            if kol is not None:

                return JsonResponse({'code': 1, 'text': sentences, 'text2': kol})
            else:
                return JsonResponse({'code': 0, 'msg': "查询异常，数据2为空"})
        else:
            return JsonResponse({'code': 0, 'msg': "查询异常，数据1为空"})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': "查询异常，后端错误,具体错误：" + str(e)})


def add_history(request):
    """增加该用户的搜索历史记录"""
    data = json.loads(request.body.decode('utf-8'))
    try:
        obj_hist = History(text=data['text'], username=data['username'])

        obj_hist.save()
        # 使用orm获取所有用户信息，并把对象转化为字典
        obj_hists = History.objects.all().values()
        hists = list(obj_hists)
        return JsonResponse({'code': 1, 'data': hists})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '搜索出现异常，具体异常如下：' + str(e)})


def get_history(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # get只能取一个数据 利用 filter可以提取多条，filter限制提取谁，values表示提取的值
        obj_hists = History.objects.filter(username=data['username']).values('text', 'add_time', 'username','Ner','Re')
        hists = list(obj_hists)
        return JsonResponse({'code': 1, 'data': hists})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg ': "获取历史记录失败" + str(e)})


def query_hist(request):
    """查询数据"""
    # 接受传递来的查询条件
    data = json.loads(request.body.decode('utf-8'))
    try:
        object_hists = History.objects.filter(username=data['username']).values()
        object_hist = object_hists.filter(Q(text=data['inputstr'])
                                          |Q(Ner=data['inputstr'])|Q(Re=data['inputstr'])).values()
        hist = list(object_hist)
        hists = list(object_hists)
        if object_hist.count() != 0:
            return JsonResponse({'code': 1, "data": hist})
        else:
            return JsonResponse({'code': 0, "msg": "不存在该记录"})
    except Exception as e:
        # 失败则返回捕捉到的错误
        return JsonResponse({"code": 0, "msg": "查询搜索记录异常:具体错误是" + str(e)})


# 删除数据单条
def delete_search(request):
    data = json.loads(request.body.decode("utf-8"))
    try:
        obj_search = History.objects.get(username=data['username'], text=data['text'], add_time=data['add_time'])
        obj_search.delete()
        obj_hists = History.objects.all().values()
        hists = list(obj_hists)
        return JsonResponse({'code': 1, 'data': hists})
    except Exception as e:
        return JsonResponse({"code": 0, "msg": "删除失败！！" + str(e)})


# 删除多条
def delete_searches(request):
    data = json.loads(request.body.decode("utf-8"))
    try:
        # 遍历传递的集合
        for one_search in data['search']:
            obj_search = History.objects.get(username=one_search['username'], text=one_search['text'],
                                             add_time=one_search['add_time'])
            # 删除
            obj_search.delete()
        obj_hists = History.objects.all().values()
        hists = list(obj_hists)
        return JsonResponse({'code': 1, 'data': hists})
    except Exception as e:
        return JsonResponse({"code": 0, "msg": "批量删除失败！！" + str(e)})


# 获取随机字符
def get_random_str():
    # 获取uuid的随机数
    uuid_val = uuid.uuid4()
    # 获取uuid的随机数字符串
    uuid_str = str(uuid_val).encode('utf-8')
    # 获取md5实例
    md5 = hashlib.md5()
    # 拿取uuid的md5摘要
    md5.update(uuid_str)
    # 返回固定长度的字符串
    return md5.hexdigest()


def export_search_excel(request):
    """导出数据到excel"""
    obj_searches = History.objects.all().values()
    searches = list(obj_searches)
    # 准备名称
    excel_name = get_random_str() + ".xlsx"
    # 准备写入的路径
    path = os.path.join(settings.MEDIA_ROOT, excel_name)
    # 写入excel
    write_to_excel(searches, path)
    # 返回
    return JsonResponse({'code': 1, 'name': excel_name})


def write_to_excel(data: list, path: str):
    """把数据库写入到Excel"""
    # 实例化一个workbook
    workbook = openpyxl.Workbook()
    # 激活一个sheet
    sheet = workbook.active
    # 为sheet命名
    sheet.title = 'search_hist'
    # 准备keys
    keys = data[0].keys()
    # 准备写入数据
    for index, item in enumerate(data):
        # 遍历每一个元素
        for k, v in enumerate(keys):
            sheet.cell(row=index + 1, column=k + 1, value=str(item[v]))
    # 写入到文件
    workbook.save(path)
